/**
 *
 * Lockbox
 * a Password and Secret Information Manager
 *
 * Created by Nathan Black
 */

#import <CoreFoundation/CoreFoundation.h>
#import <Foundation/Foundation.h>
#import <UIKit/CDStructures.h>
#import <UIKit/UIWindow.h>
#import <UIKit/UIView-Hierarchy.h>
#import <UIKit/UIHardware.h>
#import <UIKit/UITable.h>
#import <UIKit/UITableCell.h>
#import <UIKit/UITableColumn.h>
#import <UIKit/UIImageAndTextTableCell.h>
#import <WebCore/WebFontCache.h>
#import "LockboxApp.h"


@interface LockboxApp (Private)

- (void)setupMainUI;
- (void)addEditOrDeleteItem:(LockboxItem*)item itemDeleted:(BOOL)itemDeleted;
- (void)alertUser:(NSString*)header exception:(NSException*)ex;

@end

@implementation LockboxApp

- (void)dealloc
{
    [_listView release];
    [_window release];

	[super dealloc];
}

////////////// Event Handlers ///////////////
- (void) applicationDidFinishLaunching: (id) unused
{    
    NSString* homedir = @"/var/root/Library/Lockbox";
    if (![[NSFileManager defaultManager] fileExistsAtPath:homedir])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:homedir attributes:nil];
    }

    _storage = [[LockboxStorage alloc] init];

    // init main window here
    _window = [[UIWindow alloc] initWithContentRect: [UIHardware
        fullScreenApplicationContentRect]];
       
    [_window orderFront: self];
    [_window makeKey: self];
    [_window _setHidden: NO];
    
    struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
    rect.origin.x = rect.origin.y = 0.0f;

    _pwView = [[LockboxPasswordView alloc] initWithFrame:rect storage:_storage app:self];    
    _transView = [[UITransitionView alloc] initWithFrame:rect];
    [_transView addSubview:_pwView];
    [_window setContentView: _transView]; 
    
}

- (void)alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button
{
    [sheet dismiss];
}

- (void)alertUser:(NSString*)header exception:(NSException*)ex
{
    UIAlertSheet *infoSheet = [[UIAlertSheet alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    [infoSheet setTitle:header];
    [infoSheet setBodyText:[ex reason]];
    [infoSheet addButtonWithTitle:@"OK"];
    [infoSheet setDelegate:self];
    [infoSheet setAlertSheetStyle:0];
    [infoSheet presentSheetFromAboveView:[[UIWindow keyWindow] contentView]];
}

- (void)applicationWillTerminate
{
    if (_editingItem) {
        [self addEditOrDeleteItem:[_itemView item] itemDeleted:FALSE];
    }
    
    @try {
        NSLog(@"Saving user data...");
        [_storage save];
    }
    @catch (NSException* ex) {
        NSLog(@"***Caught exception during save: %@ reason: %@", [ex name], [ex reason]);
    }
}

- (void)setupMainUI
{
    struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
    rect.origin.x = rect.origin.y = 0.0f;

    _listView = [[LockboxListView alloc] initWithFrame:rect storage:_storage app:self];
    _itemView = [[LockboxItemView alloc] initWithFrame:rect app:self];
    //[_transView setDelegate: self];
    [_transView insertSubview:_listView below:_pwView];
    [_transView insertSubview:_itemView below:_listView];

}

- (void)transToItemView:(LockboxItem*)item cell:(LockboxTableCell*)cell
{
    NSLog(@"This is transToItemView");
    _lastCell = cell;
    [_itemView setItem:(item == NULL ? [[LockboxItem alloc] init] : item)];
    _editingItem = TRUE;
    [_transView transition:1 fromView:_listView toView:_itemView];
}

- (void)transToListView:(LockboxItem*)item itemDeleted:(BOOL)itemDeleted
{
    NSLog(@"This is transToListView: item: %@ itemDeleted: %d", item, (int)itemDeleted);
    [self addEditOrDeleteItem:item itemDeleted:itemDeleted];
    _editingItem = FALSE;
    [_transView transition:2 fromView:_itemView toView:_listView];
}

- (void) pwViewFinished
{
    if (_listView == NULL) {
        // user authenticated, as we haven't started up yet.
        [self setupMainUI];
        /* 3: slide up 4: slide down? */
        [_transView transition:4 fromView:_pwView toView:_listView];
    }
}

- (void)addEditOrDeleteItem:(LockboxItem*)item itemDeleted:(BOOL)itemDeleted
{
    // Check the lastCell as we're deleting, as the user may have clicked delete while adding
    if (itemDeleted && _lastCell != NULL) {
        NSLog(@"Deleting item");
        [[_storage items] removeObject:item];
        // TODO: it would be nice to just delete one item instead of rebuilding the table.
        [_listView refresh];
    }
    else if (_lastCell != NULL) {
        NSLog(@"Updating item: %@", item->key);
        [_lastCell refresh];
    }
    else {
        if (item->key != NULL && [item->key length] > 0) {
            NSLog(@"Adding item: %@", item->key);
            [[_storage items] addObject:item];
            [_listView refresh];
        }
        // otherwise don't add a blank item, and the table & storage stay the same
        // Also condition if itemView never loaded (ie user exited from PW Auth screen)
    }
}

/*- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
 NSLog(@"LBApp: Requested method for selector: %@", NSStringFromSelector(selector));
 return [super methodSignatureForSelector:selector];
}

- (BOOL)respondsToSelector:(SEL)aSelector {
NSLog(@"LBApp: Request for selector: %@", NSStringFromSelector(aSelector));
return [super respondsToSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
 NSLog(@"LBApp: Called from: %@", NSStringFromSelector([anInvocation selector]));
[super forwardInvocation:anInvocation];
}
*/

@end
